package com.mgface.thymeleaf.eventbus.a5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

public class UserThread extends Thread {
	private Socket socket;
	private EventBus eventBus;
	private BufferedReader in;
	private PrintWriter out;

	public UserThread(Socket socket, EventBus eventBus) {
		this.socket = socket;
		this.eventBus = eventBus;
		try {
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream(), true);
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	@Subscribe
	public void recieveMessage(String message) {
		if (out != null) {
			out.println(message);
			System.out.println("recieveMessage:" + message);
		}
	}

	@Override
	public void run() {
		try {
			String input;
			while ((input = in.readLine()) != null) {
				eventBus.post(input);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		// reached eof
		eventBus.unregister(this);
		try {
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		in = null;
		out = null;
	}
}
